/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    15/10/20
 **/
'use strict';
var es = require('event-stream');
let gulp =require('gulp');
let co  =require('co');
let path  =require('path');

let staticSource = [
   "statics/image/README.md"
];

gulp.task('cdn-common',function(){
  gulp.src(
     staticSource,
     { base: '.' })
     .pipe(transferFile({}))
     .pipe(end());
});


let through = require('through2');
let request  =require('request');
let fs =require('fs');

function transferFile (params) {
  params = Object.assign({}, {relativePath: '.'}, params); //暂时加这个参数 , 没有其他的好办法.
  
  return through.obj(function (file, enc, cb) {
    if (file.isNull()) {
      this.push(file);
      cb();
    } else if (file.stat.isFile()) {
      var uploadPath = file.path;//replace(new RegExp('\\\\', 'g'), '/')
      uploadPath = uploadPath.replace(path.join(__dirname,'..'), '');
      if (file.base && file.base != '.') {
        var begIndex = file.path.indexOf(file.base) + file.base.length;
        uploadPath = file.path.substring(begIndex);
      }
      uploadPath = uploadPath.replace(new RegExp('\\\\', 'g'), '/');
      var _this =this;
      
      co((function * (){
        request.post('http://127.0.0.1:3333/resources/upload',{
          form:{
            uploadPath,
            fileContents:file.contents.toString()
          }
        });
      })()).then(()=>{
        _this.push(file);
        cb();
      },err=>{
        console.error(err);
        throw err;
        //cb();
      });
      //return file;
    } else {
      this.push(file);
      cb();
    }
  });
}


function end(params){
  return es.mapSync(function (file) {
  });
};